<template>
  <view>
    <view class="uni-padding-wrap uni-common-mt">
      <uni-forms ref="form" :modelValue="form" :rules="rules" validateTrigger="blur">
        <uni-forms-item required label="昵称:" name="nickname">
          <uni-easyinput requiredtype="text" v-model="form.nickname" validateTrigger='blur' placeholder="请输入昵称，用于抽奖" />
        </uni-forms-item>
        <uni-forms-item required label="微信号:" name="wx">
          <uni-easyinput type="text" v-model="form.wx" placeholder="请输入微信号" />
        </uni-forms-item>
        <uni-forms-item required label="城市:" name="birthCity" >
          <uni-easyinput type="text" v-model="form.birthCity" placeholder="请输入出生城市" />
        </uni-forms-item>
        <uni-forms-item required label="县/区:" name="birthArea">
          <uni-easyinput type="text" v-model="form.birthArea" placeholder="请输入出生的县/区" />
        </uni-forms-item>
        <uni-forms-item required label="性别" name="sex">
          <cc-radioBtnBox  v-model="form.sex" :attrArr="meta.genderAttr" :selIndexArr="[]" @change="handleGenderChange"></cc-radioBtnBox>
        </uni-forms-item>
        <uni-forms-item required label="生辰" name="solarScxx">
          <view class="uni-input" @click="selectDate">{{birthday}}</view>
          <datePicker ref="pickerRef" @submit="handleBirthdayDate" title="出生时间选择" maskColor="rgba(0,0,0,0.3)"
                      :defaultDate="defaultDate" :defaultLunar="defaultLunar" />
        </uni-forms-item>

        <template v-for="(item, index) in form.nb">
          <uni-card style="margin: 0px;">
            <uni-forms-item :key="'year_' + item.id" required label="年份:" :name="['nb', index, 'year']" :rules="[{'required': true, errorMessage: '年份必须填写'},{validateFunction:validYear, errorMessage: '只能输入四位数字'},{format: 'number', errorMessage: '只能输入四位数字'}]">
              <uni-easyinput type="text" v-model="form.nb[index].year" placeholder="请输入年份" @change="event=>handleYearChange(index, event)"/>
            </uni-forms-item>

            <uni-forms-item :key="'jx_' + item.id" required label="吉凶" :name="['nb', index, 'jx']" :rules="[{'required': true,errorMessage: '吉凶必须选择'}]">
              <cc-radioBtnBox v-model="form.nb[index].jx" :attrArr="luckyArr" :selIndexArr="[]" @change="event=>handleLuckyChange(index, event)"></cc-radioBtnBox>
            </uni-forms-item>
            <!--						<view class="uni-list">-->
            <!--							<view class="uni-list-cell">-->
            <!--								<view class="uni-list-cell-left" style="width: 60%;padding-left: 0px;">-->
            <!--									<uni-forms-item :key="'year_' + item.id" required label="年份:" :name="['nb', index, 'year']" :rules="[{'required': true, errorMessage: '年份必须填写'},{validateFunction:validYear, errorMessage: '只能输入四位数字'},{format: 'number', errorMessage: '只能输入四位数字'}]">-->
            <!--										<uni-easyinput type="text" v-model="form.nb[index].year" placeholder="请输入年份" @change="event=>handleYearChange(index, event)"/>-->
            <!--									</uni-forms-item>-->
            <!--								</view>-->
            <!--								<view class="uni-list-cell-db">-->
            <!--									<uni-forms-item :key="'jx_' + item.id" required label="" :name="['nb', index, 'jx']" :rules="[{'required': true,errorMessage: '吉凶必须选择'}]">-->
            <!--										<cc-radioBtnBox v-model="form.nb[index].jx" :attrArr="luckyArr" :selIndexArr="[]" @change="event=>handleLuckyChange(index, event)"></cc-radioBtnBox>-->
            <!--									</uni-forms-item>-->
            <!--								</view>-->
            <!--							</view>-->
            <!--						</view>-->
            <uni-forms-item class="uni-form-item uni-column" :name="['nb', index, 'detail']" :rules="[{'required': true, errorMessage: '描述必须填写'}]">
							<textarea :key="'detail_' + index" class="tabEditor" v-model="form.nb[index].detail"
                        placeholder="请描述该年份的重大事情经历，例如被提拔，升职加薪。（至少5个字，最多300字）"></textarea>
            </uni-forms-item>
            <view class="uni-form-item uni-column">
              <button type="warn" size="mini" @click="removeItem(index)">删除</button>
            </view>
          </uni-card>
        </template>
        <view class="uni-btn-v" style="text-align: center;">
          <button type="primary" plain="true" size="mini"
                  @click="addYearStatus()">➕添加年表(重点年份越多，分析的越详细)</button>
        </view>
        <view class="uni-form-item uni-column">
          <view class="title">个人概况</view>
          <v-tabs v-model="current" :tabs="meta.tabs" @change="changeTab" zIndex="0">
          </v-tabs>
          <view id="tab0" v-show="current === 0">
						<textarea v-model="form.zhiye" class="tabEditor"
                      placeholder="请输入您的职业，例如公务员、老师，淘宝店主、程序员、无业、做某某行业生意的等等"></textarea>
          </view>
          <view id="tab1" v-show="current === 1">
						<textarea v-model="form.shenjia" class="tabEditor"
                      placeholder="请输入您的身价和年收入，例如身价500万，年收入60万"></textarea>
          </view>
          <view id="tab2" v-show="current === 2">
						<textarea v-model="form.chushen" class="tabEditor"
                      placeholder="请输入您的家庭出身情况，例如父母是当官的，做生意的，农民等等，家境好坏情况。自己的学历情况也可以写写"></textarea>
          </view>
          <view id="tab3" v-show="current === 3">
            <textarea v-model="form.jiankang" class="tabEditor" placeholder="请输入您的健康情况，例如有颈椎病、胃病、肝病、尿结石、妇科疾病、伤残等等"></textarea>
          </view>
          <view id="tab4" v-show="current === 4">
						<textarea v-model="form.hunyin" class="tabEditor"
                      placeholder="请输入您的婚姻子女情况，例如a1.离过婚，离婚年份。 a2:婚姻不顺，经常吵架。 a3.婚姻美满 a4.没结过婚 b1. 一个儿子，18年出生 b2.无儿无女"></textarea>
          </view>
          <view id="tab5" v-show="current === 5">
						<textarea v-model="form.zinv" class="tabEditor"
                      placeholder="请输入您的子女情况，例如1. 一儿一女，儿子2018年出生，女儿2020年出生 2.无儿无女 "></textarea>
          </view>
          <view id="tab6" v-show="current === 6">
						<textarea v-model="form.xingge" class="tabEditor"
                      placeholder="请输入您的性格特点。例如1:急性子2.慢条斯理的性子 3.暴躁如雷 4.温文尔雅 5.出口伤人 6.内心阴暗 7.内心光明 8.抑郁寡欢"></textarea>
          </view>
        </view>
        <view class="uni-btn-v">
          <button  type="primary" @click="formSubmit()">提交</button>
          <button type="simple" @click="back()">返回</button>
        </view>
      </uni-forms>
    </view>
  </view>
</template>

<script>
import axios from 'axios'
import graceChecker from "../../../common/graceChecker.js"
import datePicker from '/uni_modules/nj-birthday-picker/components/nj-birthday-picker/nj-birthday-picker.vue'

function getDate(type) {
  const date = new Date();

  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  let hour = date.getHours();
  let mintue = date.getMinutes();

  console.log(hour + "--->" + mintue);

  if (type === 'start') {
    year = year - 10;
  } else if (type === 'end') {
    year = year + 10;
  }
  month = month > 9 ? month : '0' + month;;
  day = day > 9 ? day : '0' + day;

  return `${year}-${month}-${day} ${hour}:${mintue}`;
}

function zeroPaddingForce(num) {
  return num.toString().padStart(2, "0");
}

function formatDate(date) {

  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  let hour = date.getHours();
  let mintue = date.getMinutes();

  month = month > 9 ? month : '0' + month;;
  day = day > 9 ? day : '0' + day;

  return `${year}-${month}-${day} ${hour}:${mintue}`;
}

export default {
  components: {
    datePicker,
  },
  created() {
    console.log(JSON.stringify(this.rules));
  },
  data() {
    return {
      meta: {
        genderAttr: [{
          attr: '',
          value: ['渣男', '渣女']
        }],
        tabs: ['职业', '年收入', '出身', '健康', '婚姻', '子女', '性格'],
        genders: ["男", "女"],
      },
      birthday: " ",
      item_0_year: "2010",
      item_0_jx: " ",
      cardObj: {},
      form: {
        nickname: "",
        wx: "",
        birthCity: "",
        birthArea: "",
        sex: "",
        birthday: " ",
        solarScxx: "",
        lunarScxx: "",
        nb: [{
          "year": "",
          "jx": "",
          "detail": ""
        }],
        zhiye: "",
        shenjia: "",
        chushen: "",
        jiankang: "",
        hunyin: "",
        zinv: "",
        xingge: "",
      },
      rules: {
        nickname: {
          rules: [{
            required: true,
            errorMessage: '请输入姓名',
          },
            // {
            // 	minLength: 3,
            // 	maxLength: 5,
            // 	errorMessage: '姓名长度在 {minLength} 到 {maxLength} 个字符',
            // },
            {
              validateFunction: async function (rule, value, data, callback) {
                const formData = new FormData();
                formData.append('nickname', value);
                const response = await axios.post('https://zhixiaoyixue.com:86/checkNickname', formData,
                    {
                      headers: {
                        'Content-Type': 'multipart/form-data'
                      }
                    },
                );
                return response.data.usable[0];
              },
              errorMessage: '昵称重复了, 请换一个!',
              validateTrigger: 'blur'
            },
          ]
        },
        wx: {
          rules: [{
            required: true,
            errorMessage: '请输入微信号',
          }
          ]
        },
        birthCity: {
          rules: [{
            required: true,
            errorMessage: '请输入城市',
          }
          ]
        },
        birthArea: {
          rules: [{
            required: true,
            errorMessage: '请输入县/区',
          }
          ]
        },
        sex: {
          rules: [{
            required: true,
            errorMessage: '请选择性别',
          }
          ]
        },
        solarScxx: {
          rules: [{
            required: true,
            errorMessage: '请输入出生时间',
          }
          ]
        }
      },
      selIndexArr: [0, 0, 0, 0],
      current: 0,
      selLuckyArr: [0, 0],
      luckyArr: [{
        attr: '',
        value: ['吉', '凶']
      }],
      title: 'picker',
      array: [{
        name: '知晓老师'
      }, {
        name: '其它老师'
      }],
      date: getDate({
        format: true
      }),
      startDate: getDate('start'),
      endDate: getDate('end'),
      defaultDate: new Date(),
      defaultLunar: false,
      date: "",
      dateObj: {},
      timeObj: {},
    }
  },
  methods: {
    addYearStatus: function (e) {
      this.form.nb.push({
        "year": "",
        "jx": "",
        "detail": ""
      });
      //this.initRules();
    },
    validYear: function (rule, value, data, callback) {
      if (value < 1000) {
        return false;
      }
      value = "" + value;
      console.log(value);
      if (value.length > 4) {
        console.log(value + " " + false);
        return false;
      }
      console.log(value + " " + true);
      return true;
    },
    genderRadioChange: function (e) {
      this.form.gender = e.detail.value;
    },
    bindPickerChange: function (e) {
      console.log('picker发送选择改变，携带值为：' + e.detail.value)
      this.index = e.detail.value
    },
    // 去选择生日
    selectDate() {
      this.$refs.pickerRef.show();
    },
    openDatetimePicker: function (e) {
      openDatetimePicker1();
    },
    // 选择生日回调
    handleBirthdayDate(res) {
      this.dateObj = res;
      this.form.lunarScxx = res.lYear + res.gzYear + "年" + res.IMonthCn + res.IDayCn + res.hour + "时" + res.minute + "分";
      //this.form.lunarScxx = res.lYear + "-" + zeroPaddingForce(res.lMonth) + "-" + zeroPaddingForce(res.lDay) + " " + res.hour + ":" + res.minute;
      this.form.solarScxx = res.cYear + "-" + zeroPaddingForce(res.cMonth) + "-" + zeroPaddingForce(res.cDay) + " " + res.hour + ":" + res.minute;

      console.log("lunar: " + this.form.lunarScxx + "solar: " + this.form.solarScxx);

      if (res.isLunar) {
        this.birthday = "农历" + this.form.lunarScxx;
      } else {
        this.birthday = "阳历" + this.form.solarScxx;
      }
    },
    bindDateChange: function (index, e) {
      console.log("index:" + index);
      console.log("e:" + JSON.stringify(e.detail.value));
      this.form.nb[index].year = e.detail.value
    },
    bindTimeChange: function (e) {
      this.time = e.detail.value
    },
    formSubmit: async function (e) {
      console.log('表单数据信息：', JSON.stringify(this.form));

      let isValid = false; // 标志变量

      try {
        await this.$refs.form.validate();
        isValid = true; // 如果验证成功，设置标志为 true
      } catch (err) {
        console.log('表单错误信息：', err);
        uni.showToast({
          title: err[0].errorMessage,
          icon: "none"
        });
      }

      if (!isValid) {
        return;
      }

      // this.$refs.form.validate().then(res=>{
      //
      // }).catch(err =>{
      // 	console.log('表单错误信息：', err);
      // 	uni.showToast({
      // 		title: err[0].errorMessage,
      // 		icon: "none"
      // 	});
      // 	return;
      // })

      const fetchData = async () => {
        try {
          console.log("send request...2");
          const response = await axios.post('https://zhixiaoyixue.com:86/save', this.form);
          console.log(response.data);

          if (response.data.result[0] == 0) {
            uni.showToast({
              title: "保存成功！",
              icon: "none"
            });
            window.location.href = 'http://zhixiaoyixue.com/pages/component/contributeList/contributeList2';
            // this.$router.push({
            // 	path: '/pages/component/contributeList/contributeList',
            //   force: true
            // });
          } else {
            uni.showToast({
              title: "保存信息失败, 城市和县区可能填写有误",
              icon: "none"
            });
            // uni.showModal({
            // 	title: "保存信息失败",
            // 	content: "保存信息失败, 城市和县区可能填写有误",
            // 	icon: "none"
            // });
          }
        } catch (error) {
          console.error('Fetch error:', error);
        }
      };

      console.log("send request...1");
      await fetchData();
    },
    formReset: function (e) {
      console.log('清空数据')
    },
    changeTab: function (index) {
      console.log('当前选中索引：' + index)
    },
    removeItem: function (index) {
      console.log('当前删除索引：' + index)
      if (this.form.nb.length > 1) {
        this.form.nb.splice(index, 1); // 从数组中移除指定索引的项
      }
      console.log(index, this.form.nb)
    },
    back: function () {
      this.$router.go(-1);
    },
    handleYearChange: function (index, e) {
      console.log("index:" + index + " " + JSON.stringify(e))
      this.form.nb[index].year = e;
    },
    handleLuckyChange: function (index, e) {
      console.log("index" + index + " " + JSON.stringify(e))
      if (e[0] == 0) {
        this.form.nb[index].jx = '吉';
      } else {
        this.form.nb[index].jx = '凶';
      }
    },
    handleGenderChange: function (e) {
      console.log(JSON.stringify(e))
      if (e[0] == 0) {
        this.form.sex = "男";
      } else {
        this.form.sex = "女";
      }
    }
  }
}
</script>

<style>

.wrap {
  padding: 20px;

  button {
    margin-bottom: 20px;
  }
}

.tabEditor {
  border: 1px solid #ccc;
  width: 100%;
  background-color: white;
}

.activeTab {
  display: block;
}
</style>